<template>
  <div>
    <form-create
        v-model="fApi"
        :rule="rule"
        :option="option"
        style="margin: 30px;"
    ></form-create>
  </div>
</template>

<script>
  import formCreate from "@form-create/element-ui";
  import {parseShareLinkJwt, selectById} from './api'

  export default {
    name:'TmptDynamicFormPortal',
    props:{
    },
    data () {
      return {
        fApi: null,
        rule:[],
        option:{},
      }
    },
    watch:{
    },
    computed:{
      jwt() {
        if (!this.$route || !this.$route.query) {
          return undefined
        }
        return this.$route.query.jwt
      }
    },
    mounted() {
      this.initFormSheet()
    },
    methods: {
      getFApi() {
        return this.fApi
      },
      getElVm(fieldId) {
        const vm = this.fApi.el(fieldId)
        return vm
      },
      // 通过 dynamicFormId 自动加载新的表单页面
      async initFormSheet() {
        if (!this.jwt) return
        console.log('this.jwt')
        console.log(this.jwt)

        const resultJwt = await parseShareLinkJwt({"jwt":this.jwt})
        if (!resultJwt.success) {
          this.$message.error(resultJwt.content);
          return
        }
        const dynamicFormId = resultJwt.obj.dynamicFormId
        const expandData = resultJwt.obj.expandData

        const result = await selectById({"id":dynamicFormId})
        if (!result.success) {
          this.notify(result)
          return
        }
        this.rule =  formCreate.parseJson(result.obj.rule)
        this.option = formCreate.parseJson(result.obj.option)

        // 等页面渲染显示出来后，加载数据内容
        console.log('自动加载参数this.param')
        console.log(this.param)
        this.$nextTick(()=>{
          const fields = this.fApi.fields()
          fields.forEach(fieldId=>{
            // 找组件 loadDataAuto，并调用其 loadData(), 完成数据加载
            const vm = this.fApi.el(fieldId)
            const formCreateInject = vm.formCreateInject
            if (formCreateInject && formCreateInject.prop.type==='loadDataAuto') {
              vm.loadData(this.param)
            }
          })
        })

      },
    }
  }
</script>
